package com.song.tools.songtest.constants;

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.song.tools.core.enums.IntegerCodeBaseEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * <p>
 * 字典状态枚举
 * </p>
 *
 * @author pine
 * @since 2024-05-15
 */
@AllArgsConstructor
@Getter
public enum StatusEnum implements IntegerCodeBaseEnum {
    ENABLE(1, "启用"),
    DISABLE(0, "禁用"),
    ;

    @EnumValue
    private final Integer code;
    private final String desc;

    public static StatusEnum of(Integer code) {
        return Arrays.stream(StatusEnum.values()).filter(statusEnum -> Objects.equals(statusEnum.code, code)).findAny().orElse(null);
    }


    @NoArgsConstructor
    public static class JsonSerializer extends com.fasterxml.jackson.databind.JsonSerializer<StatusEnum> {
        public void serialize(StatusEnum value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeNumber(value.getCode());
        }
    }

    @NoArgsConstructor
    public static class JsonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<StatusEnum> {

        @Override
        public StatusEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
            String jsonCode = jsonParser.getValueAsString();
            if (jsonCode == null) {
                return null;
            } else {
                StatusEnum[] values = StatusEnum.values();
                Integer code = null;
                try {
                    code = Integer.parseInt(jsonCode);
                } catch (Exception e) {
                }

                final Integer finalCode = code;
                return Arrays.stream(values).filter((item) -> {
                    return Objects.equals(item.getDesc(), jsonCode) || Objects.equals(item.getCode(), finalCode);
                }).findAny().orElse(null);
            }
        }
    }


}
